//
//  NRLSVMTViewController+Request.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-12.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "NRLSVMTViewController+Request.h"
#import "MBProgressController.h"
#import "Network_Operation.h"
#import "CMNavigationController.h"
#import "KeychainItemWrapper.h"
#define KEY_UUID @"com.svmt.nari_UUID"
@implementation NRLSVMTViewController (Request)

-(void)NRLSMTUserLogin
{
    [[MBProgressController sharedInstance] showWithText:@"正在努力加载..."];
    WeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *loginStr = [Network_API Network_API_Login];
        
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:loginStr];
        NSString    *tmpUserName = [[User sharedInstance] userName];
        NSString    *tmpPassWord = [[User sharedInstance] userPassword];
        NSString    *tmpUUID    = [[User sharedInstance] uuId];
        
        NSString    *str = [NSString stringWithFormat:@"[{\"classname\":%@,\"methodname\":%@,\"parameterClasss\":[{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@},{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@},{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@}]}]",@"\"iPadSettingService\"",@"\"login\"",@"\"userName\"",tmpUserName,@"\"java.lang.String\"",@"\"password\"",tmpPassWord,@"\"java.lang.String\"",@"\"uuid\"",tmpUUID,@"\"java.lang.String\""];
        [httpClient postPath:loginStr
                  parameters:@{@"jsonstr":str,
                               @"callback":@""
                               }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         if([responseObject isKindOfClass:[NSString class]])
                         {
                             NSString *resStr = [NSString stringWithString:responseObject];
                             if(!([resStr rangeOfString:@"id"].location == NSNotFound))
                             {
                                 //call TCP connect:
                                 NSLog(@"Login Success");
                                 
                                 NSInteger indexSubStr = [resStr rangeOfString:@"id"].location;
                                 NSString   *subString = [resStr substringWithRange:NSMakeRange(indexSubStr, resStr.length-indexSubStr)];
                                 if(!([subString rangeOfString:@","].location == NSNotFound))
                                 {
                                     NSInteger endIndex = [subString rangeOfString:@","].location;
                                     NSString   *resultStr = [subString substringWithRange:NSMakeRange(5, endIndex-1-5)];
                                     NSLog(@"%@",resultStr);
                                     subjectId = resultStr;//屏幕预览所用到的userid
                                 }
                                 /*****************写用户名和密码缓存******************/
//                                 if(wself.reInputName == YES)
//                                 {
                                     if([wself.dLoginInfofm fileExistsAtPath:wself.dLoginInfopath] == YES)
                                     {
                                         [wself.dLoginInfofm removeItemAtPath:wself.dLoginInfopath error:nil];
                                     }
                                     if([wself.dLoginInfo_PassWordfm fileExistsAtPath:wself.dLoginInfo_PassWordpath] == YES)
                                     {
                                         [wself.dLoginInfo_PassWordfm removeItemAtPath:wself.dLoginInfo_PassWordpath error:nil];
                                     }
                              //   }
                                 /********写本地登录信息***********/
                                 if([wself.dLoginInfofm fileExistsAtPath:wself.dLoginInfopath] == NO)
                                 {
                                     NSDictionary *tmpParams = [NSDictionary dictionaryWithObjectsAndKeys:wself.userNameText.text,@"userNameText", nil];
                                     
                                     NSData *params = [NSKeyedArchiver archivedDataWithRootObject:tmpParams];
                                     if([wself.dLoginInfofm createFileAtPath:wself.dLoginInfopath contents:params attributes:nil] == NO)
                                     {
                                         NSLog(@"create LoginInfo buffer file failure!");
                                     }
                                     
                                 }
                                 if([wself.dLoginInfo_PassWordfm fileExistsAtPath:wself.dLoginInfo_PassWordpath] == NO)
                                 {
                                     NSDictionary *tmpParams = [NSDictionary dictionaryWithObjectsAndKeys:wself.userPassword.text,@"userPassword", nil];
                                     NSData *params = [NSKeyedArchiver archivedDataWithRootObject:tmpParams];
                                     
                                     if([wself.dLoginInfo_PassWordfm createFileAtPath:wself.dLoginInfo_PassWordpath contents:params attributes:nil] == NO)
                                     {
                                         NSLog(@"create PassWord buffer file failure!");
                                     }
                                 }
                                 //设备连接
                                 TcpClient *tcp = [TcpClient sharedInstance];
                                 NSString *requestStr = [NSString stringWithFormat:@"{\"messageData\":\"%@\",\"messageType\":%d}",@"",3];
                                 [tcp writeString:requestStr];
                                 /**********************************************/
                                 //页面跳转到主题页面：
                                 self.subjectViewController = [[NRLSVMTSubjectViewController alloc] initWithNibName:@"NRLSVMTSubjectViewController" bundle:nil];
                                 
                                 UINavigationController *subjectNC = [[UINavigationController alloc] initWithRootViewController:self.subjectViewController];
                                 
                                 [self presentViewController:subjectNC animated:NO completion:nil];
                             }
                             else
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     [[MBProgressController sharedInstance] hide];
                                     NSString *tmpstr = responseObject;
                                     NSString *strr = [tmpstr substringFromIndex:1];
                                     NSString *str = [strr substringToIndex:1];
                                     if([str isEqualToString:@"-"]){
                                    [[MBProgressController sharedInstance] showTipsOnlyText:@"用户名或密码错误" AndDelay:1.5];
                                     }
                                     if([str isEqualToString:@"0"]){
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"设备未注册" AndDelay:1.5];
                                     }
                                    if([str intValue] == -1){
                                         [[MBProgressController sharedInstance] showTipsOnlyText:@"用户名或密码错误" AndDelay:1.5];
                                     }
                                 });
                                 NSLog(@"直接返回");
                             }
                         }
                         else {
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 [[MBProgressController sharedInstance] hide];
                                 NSString *tmpstr = responseObject;
                                 NSString *strr = [tmpstr substringFromIndex:1];
                                 NSString *str = [strr substringToIndex:1];
                                 if(![str intValue]){
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"设备未注册" AndDelay:1.5];
                                     

                                 }
                                 else if([str intValue] == -1){
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"用户名或密码错误" AndDelay:1.5];
                                 }
                             });
                             NSLog(@"直接返回");

                         }
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [[MBProgressController sharedInstance] hide];
                             [[MBProgressController sharedInstance] showTipsOnlyText:@"登录失败"
                                                                            AndDelay:1.5];
                         });
                     }];
    });
}
-(NSString *) setKeyChainValue
{
    NSDictionary *strUUID = (NSMutableDictionary *)[KeychainItemWrapper load:KEY_UUID];
    if (strUUID==nil|| ![strUUID.allKeys count])
    {
        NSMutableDictionary *uuidKVPairs = [NSMutableDictionary dictionary];
        [uuidKVPairs setObject:[self gen_uuid] forKey:@"UUID_Svmt"];
        [KeychainItemWrapper save:KEY_UUID data:uuidKVPairs];
    }
    NSString *uuid = ((NSMutableDictionary *)[KeychainItemWrapper load:KEY_UUID])[@"UUID_Svmt"];
    return uuid;
}

-(NSString *) gen_uuid
{
    CFUUIDRef uuid_ref=CFUUIDCreate(nil);
    CFStringRef uuid_string_ref=CFUUIDCreateString(nil, uuid_ref);
    NSString *uuid=[NSString stringWithString:(__bridge NSString *)(uuid_string_ref)];
    return uuid;
}

@end
